<template>
  <div class="test">
    <div class="connectting">{{printMsg}}</div>
    <slot></slot>
    <header class="header-style">
      <div>
        <label for="currentUser">
          当前用户：
          {{source}}
        </label>
      </div>
      <div>
        <label for="talkTarget" class="talkTarget">
          对话对象：
          <el-input
            id="talkTarget"
            v-model="targetObj"
            class="text-input"
            maxlength="20"
            clearable
          />
        </label>
        <el-button @click="msgArr=[],inputV=''">清空</el-button>
        <el-button @click="dialogVisible=true">发起新的对话</el-button>
        <el-tooltip class="item" effect="dark" content="Enter键发送，Ctrl+Enter换行" placement="top-start">
          <li class="el-icon-question"></li>
        </el-tooltip>
      </div>
    </header>
    <main class="content">
      交互内容
      <div class="talkFrame">
        <el-scrollbar class="talkPanel" id="talkPanel" ref="scrollBar">
          <TalkFrame
            v-for="(val,index) in msgArr"
            :key="index"
            :msg="val"
            @changeTarget="changeTarget"
          ></TalkFrame>
        </el-scrollbar>
        <div class="onlineFrame">
          <OnlineFrame @clickUser="changeTarget" :onlineMsg="onlineMsg"></OnlineFrame>
        </div>
      </div>
      <div>
        <div class="content">
          <textarea
            v-model="inputV"
            class="textArea"
            placeholder="按Enter键发送,Ctrl+Enter换行"
            @keypress.enter.exact.prevent="msgSend(inputV)"
            @keydown.ctrl.enter.exact="addEnter(inputV)"
          ></textarea>
        </div>
      </div>
    </main>
    <footer>
      <el-button @click="msgSend(inputV)" class="linkStart">发送</el-button>
    </footer>
    <el-dialog :visible.sync="dialogVisible" width="275px" class="dialog">
      <ClickTalk @openTalk="dialogVisible=false"></ClickTalk>
    </el-dialog>
  </div>
</template>

<script>
import TalkFrame from "./TalkFrame.vue";
import { LoginPackage, MessagePackage, Msg } from "../Bean";
import MsgConstants from "../constants/MsgConstants";
import PacketConstants from "../constants/PacketConstants";
import { WEB_SOCKET_URL } from "../Base";
import OnlineFrame from "../components/OnlineFrame";
import ClickTalk from "../components/ClickTalk";
import { OnlineQueryPackage } from "../Bean";
export default {
  props: {
    loginReq: {
      type: LoginPackage,
      default: function() {
        return new LoginPackage("没有指定对象");
      }
    },
    source: {
      type: String,
      default: function() {
        return this.loginReq.user;
      }
    },
    target: {
      type: String
    }
  },
  data() {
    return {
      websock: null,
      inputV: "",
      msgArr: [],
      // webSockStatus:this.websock.readyState,
      connectCount: 0,
      targetObj: this.target,
      dialogVisible: false,
      onlineMsg: {}
    };
  },
  created() {
    this.changeTitle();
    this.initWebSocket();
    let historyTalk = localStorage.getItem(`${this.source}`);
    if (historyTalk) {
      this.msgArr = Array.from(
        JSON.parse(historyTalk)
      );
      console.log(this.msgArr);
    }
    if (sessionStorage.target) {
      this.targetObj = sessionStorage.target;
    }
  },
  destroyed() {
    console.log("连接断开");
    this.websock.close(); //离开路由之后断开websocket连接
  },
  computed: {
    printMsg: function() {
      return this.connectCount == 0
        ? ""
        : "正在连接，尝试次数：" + this.connectCount;
    }
  },
  watch: {
    targetObj(val) {
      this.changeTitle();
      sessionStorage.target = val;
    },
    msgArr(val) {
      console.log("此时消息：", val);
      localStorage.setItem(`${this.source}`, JSON.stringify(val));
      let _this = this;
      this.$nextTick(function() {
        _this.$refs.scrollBar.wrap.scrollTop =
          _this.$refs.scrollBar.wrap.scrollHeight;
      });
    }
  },
  methods: {
    initWebSocket() {
      //初始化weosocket
      this.websock = new WebSocket(WEB_SOCKET_URL);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      this.websocketsend(new OnlineQueryPackage());
      this.websocketsend(this.loginReq);
      console.log("连接建立成功");
    },
    websocketonerror() {
      //   连接建立失败重连
      if (this.connectCount < 5) {
        this.initWebSocket();
        console.log(this.printMsg);
        this.connectCount++;
      } else {
        this.msgArr.push(
          new Msg(
            MsgConstants.TYPE_SYSTEM,
            "连接服务器失败，请等会刷新页面后重试"
          )
        );
        this.connectCount = 0;
      }
    },
    websocketonmessage(e) {
      console.log("收到消息：" + e.data);
      this.connectCount = 0;
      let obj = JSON.parse(e.data);
      console.log(obj);
      switch (obj.command) {
        case PacketConstants.SYSTEM:
          this.msgArr.push(
            new Msg(MsgConstants.TYPE_SYSTEM, obj.content, obj.source)
          );
          break;
        case PacketConstants.COMMAN_MSG:
          this.msgArr.push(
            new Msg(MsgConstants.TYPE_REC, obj.content, obj.source)
          );
          break;
        case PacketConstants.ONLINE_QUERY:
          console.log("aaa");
          this.onlineMsg = obj;
          break;
      }
    },
    websocketsend(data) {
      if (this.websock.readyState == this.websock.CLOSED) {
        this.$message.warning("连接断开，尝试重连中。。。。。");
        this.initWebSocket();
      }
      if (this.websock.readyState == this.websock.OPEN) {
        let stringData = JSON.stringify(data);
        this.websock.send(stringData);
      }
    },
    msgSend(data) {
      if (!this.targetObj) {
        this.$message.closeAll();
        this.$message.warning("请填写要发送的对象");
        return;
      }
      //数据发送
      if (data.trim() == "") {
        this.$message.closeAll();
        this.$message.warning("请输入要发送的内容");
        this.inputV = "";
        return;
      }
      let mess = new MessagePackage(data, this.source, this.targetObj);
      this.websocketsend(mess);
      this.msgArr.push(
        new Msg(MsgConstants.TYPE_SEND, mess.content, mess.source, mess.target)
      );
      this.inputV = "";
      // localStorage.msgArr = JSON.stringify(this.msgArr);
    },
    addEnter(){
      console.log("进入")
      this.inputV = this.inputV + '\n';
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.msgArr.push(new Msg(MsgConstants.TYPE_SYSTEM, "连接已断开"));
    },
    changeTarget(val) {
      if (val) {
        this.targetObj = val;
      }
    },
    changeTitle() {
      document.title = `${this.source}${
        this.targetObj ? "和" + this.targetObj : ""
      }的对话`;
    },
    openFrame(path) {
      let routeUrl = this.$router.resolve({
        path: path
      });
      window.open(routeUrl.href, "_blank");
    }
  },
  components: {
    TalkFrame,
    OnlineFrame,
    ClickTalk
  }
};
</script>
<style scoped>
.content {
  border: 1px solid black;
  /* line-height: 20px; */
}
.talkFrame {
  /* overflow-x: auto; */
  /* overflow-y: inherit; */
  height: 500px;
  border-top: 1px solid black;
}
.textArea {
  width: 100%;
  padding: 0;
  border-width: 0;
  resize: none;
  height: 50px;
  font-size: 15px;
  background-color: transparent;
}
textarea:focus {
  outline-offset: 0px;
  outline: 0;
}
.linkStart {
  margin: 10px auto;
  display: block;
}
.text-input {
  width: 200px;
  padding: 5px;
}
.onlineFrame {
  /* width: 42%;
  word-wrap:break-word;
  background-color: rgb(190, 230, 229,0.8); */
  /* opacity:0.5 */
  display: inline-block;
  /* width: 30%; */
  border-left: 2px solid black;
  height: 500px;
  position: absolute;
  height: inherit;
}
.talkPanel {
  display: inline-block;
  width: 70%;
  /* overflow: auto; */
  height: inherit;
}
@media (max-width: 500px) {
  .onlineFrame {
    display: none;
  }
  .talkPanel {
    width: 100%;
    /* overflow: auto; */
    height: inherit;
  }
  .talkTarget {
    display: inherit;
  }
  .header-style{
    margin: 5px;
  }
}
</style>
<style>
.el-scrollbar__wrap {
  overflow-x: hidden;
  margin-bottom: 0px !important;
}
.el-dialog__body {
  background-color: transparent;
  padding: 0;
}
.el-dialog__header {
  background-color: transparent;
  padding: 0;
}
</style>